const exporess = require('express');
const Utils = require('../../../utils');
const { Users } = require('../../../models');
const Wechat = require("../../../utils/Wechat");
const Send = require('../../../utils/Send');
const Token = require('../../../utils/Token');

const router = exporess.Router();

// SSE连接对象
const sseMap = {};

/** 微信一键登录/注册 */
router.post("/login", async (req, res, next) => {
  const { code } = req.body;
  try {
    if (!code) {
      return res.send(Send.fail("code不能为空"));
    }
    const openid = await Wechat.getOpenid(code);
    if (!openid) {
      return res.send(Send.fail("获取openid失败"));
    }
    let user = await Users.findOne({ where: { openid } });
    if (!user) {
      // 创建用户
      const account = Utils.createUUID("a", 18);
      const salt = Utils.createSalt();
      const password = Utils.hashPassword("123456", salt);
      await Users.create({ account, salt, password, openid });
      user = await Users.findOne({ where: { openid } });
    }
    const token = await Token.saveToken(user);
    res.send(Send.success(token));
  } catch (error) {
    next(error);
  }
});

/** 监听微信扫码登录，SSE服务 */
router.get("/on-qr-login", async (req, res, next) => {
  const { client_uuid } = req.query;
  res.setHeader("Content-Type", "text/event-stream");
  res.setHeader("Cache-Control", "no-cache");
  res.setHeader("Connection", "keep-alive");
  // 发送注释，对于某些浏览器这是必要的，以避免过早关闭连接
  res.write("\n");
  sseMap[client_uuid] = res;
  res.on("close", () => {
    delete sseMap[client_uuid];
  });
})

/** 获取微信小程序二维码 */
router.get("/qr-code", async (req, res, next) => {
  try {
    const { client_uuid } = req.query;
    if (!client_uuid) {
      return res.send(Send.fail("非法请求"));
    }
    // 获取小程序授权页面的二维码，并携带参数
    const result = await Wechat.getAppletQrCode("pages/pclogin/pclogin", client_uuid, { check_path: false, width: 280, is_hyaline: true, });
    res.set({ 'Content-Type': 'image/png', 'Content-Length': result.length })
    res.send(result);
  } catch (error) {
    next(error);
  }
})

/** 微信扫二维码，打开小程序授权页面 */
router.post("/open-login", async (req, res, next) => {
  try {
    const { client_uuid } = req.body;
    if (!client_uuid) {
      return res.send(Send.fail("非法请求"));
    }
    if (!sseMap[client_uuid]) {
      return res.send(Send.fail("二维码已失效"));
    }
    sseMap[client_uuid].write(`data: open\n\n`); // 推送消息，通知微信扫码成功并打开了授权页面
    res.send(Send.success());
  } catch (error) {
    next(error);
  }
})

/** 微信小程序授权 */
router.post("/applet-login", async (req, res, next) => {
  try {
    const { token } = Utils.getBaseParams(req);
    const { code, client_uuid } = req.body;
    if (!code || !client_uuid) {
      return res.send(Send.fail("非法请求"));
    }
    if (!sseMap[client_uuid]) {
      return res.send(Send.fail("二维码已失效"));
    }
    // 如果有token，判断token是否有效
    if (token) {
      const info = await Token.getInfoByToken(token);
      if (info?.id) {
        // 如果token有效，则直接使用该token
        sseMap[client_uuid].write(`data: token-${token}\n\n`);
        return res.send(Send.success(token));
      }
    }
    // 如果没有token或者token无效，则使用code获取用户信息
    const openid = await Wechat.getOpenid(code);
    let user = await Users.findOne({ where: { openid } });
    if (!user) {
      // 创建用户
      const account = Utils.createUUID("a", 18);
      const salt = Utils.createSalt();
      const password = Utils.hashPassword("123456", salt);
      await Users.create({ account, salt, password, openid });
      user = await Users.findOne({ where: { openid } });
    }
    // 直接登录
    const newToken = await Token.saveToken(user);
    sseMap[client_uuid].write(`data: token-${newToken}\n\n`);
    res.send(Send.success(newToken));
  } catch (error) {
    next(error);
  }
})


module.exports = router;